package com.yami.shop.service.impl;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.bean.dto.QrStatisticsList;
import com.yami.shop.bean.model.*;
import com.yami.shop.bean.vo.CreatQrVo;
import com.yami.shop.common.annotation.RedisLock;
import com.yami.shop.common.bean.Minio;
import com.yami.shop.common.util.IdUtil;
import com.yami.shop.common.util.OssMultipartFile;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.common.util.StringUtils;
import com.yami.shop.common.util.pdfUtil.PdfUtils;
import com.yami.shop.config.ShopConfig;
import com.yami.shop.dao.ReproductionQrcodeMapper;
import com.yami.shop.service.*;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class ReproductionQrcodeServiceImpl extends ServiceImpl<ReproductionQrcodeMapper, ReproductionQrcode> implements ReproductionQrcodeService {

    @Autowired
    private IdUtil idUtil;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private Snowflake snowflake;
    @Autowired
    private QrcodeTicketService qrcodeTicketService;

    @Autowired
    private ProductService productService;

    @Autowired
    private ShopConfig shopConfig;

    @Autowired
    private ProdNftService prodNftService;
    @Autowired
    private AttachFileService attachFileService;

    @Override
    public IPage<ReproductionQrcode> pageData(PageParam<ReproductionQrcode> page, ReproductionQrcode param) {

        return this.baseMapper.pageData(page,param);
    }

    @Override
    public List<QrcodeTicket> listData(Long prodId,Long batchId,Long activityId) {

        return this.baseMapper.listData(prodId,batchId,activityId);
    }

    @Override
    public List<QrStatisticsList> viewQr(String shopId, Long activityId) {

        return this.baseMapper.viewQr(activityId);
    }

    @Override
    @Async
    @RedisLock(lockName = "presellCreateQr", key = "#creatQrVo.activityId+'-'+#creatQrVo.prodId")
    public void createQr(CreatQrVo creatQrVo) {
        // 获取二维码数量
        QueryWrapper<ReproductionQrcode> reproductionQrcodeQueryWrapper = new QueryWrapper<>();
        reproductionQrcodeQueryWrapper.eq("activity_id",creatQrVo.getActivityId());
        reproductionQrcodeQueryWrapper.eq("prod_id",creatQrVo.getProdId());
        reproductionQrcodeQueryWrapper.eq("batch_id",creatQrVo.getBatchId() + 1);
        long count = this.count(reproductionQrcodeQueryWrapper);
        if(count > 0){
            return;
        }
        String fkhUrl = sysConfigService.getValue("fkh_url");
        // 获取商品信息
        Product product = productService.getProductById(creatQrVo.getProdId());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        String certificate = getBase64(product, product.getProdId() + "", "daw" + cn.hutool.core.util.IdUtil.simpleUUID(), sdf.format(new Date()));
        List<ReproductionQrcode> reproductionQrcodes = new ArrayList<>();
        // 生成二维码
        for(int i=0;i< creatQrVo.getNum();i++){
            String ticketCode = String.valueOf(snowflake.nextId());
            String ticket = idUtil.nextShortId();
            QrcodeTicket qrcodeTicket = new QrcodeTicket();
            qrcodeTicket.setCreateTime(new Date());
            qrcodeTicket.setType(4);
            qrcodeTicket.setTicket(ticket);
            qrcodeTicket.setTicketUrl(fkhUrl + "&ticketType=4&copyrightId="+creatQrVo.getProdId()+"&ticketCode="+ticketCode+"&qrcodeType=authentication&mainProdId="+creatQrVo.getProdId());
            qrcodeTicketService.save(qrcodeTicket);
            ReproductionQrcode reproductionQrcode = new ReproductionQrcode();
            reproductionQrcode.setQrcodeId(qrcodeTicket.getTicketId());
            reproductionQrcode.setProdId(creatQrVo.getProdId());
            reproductionQrcode.setStatus("0");
            reproductionQrcode.setActivityId(creatQrVo.getActivityId());
            reproductionQrcode.setBatchId(creatQrVo.getBatchId()+1+"");
            reproductionQrcode.setQrcodeCode(ticketCode);
//            reproductionQrcode.setCertificate(certificate);
            reproductionQrcodes.add(reproductionQrcode);
        }
        // 保存复刻画二维码信息
        if(ObjectUtil.isNotEmpty(reproductionQrcodes)){
            this.saveBatch(reproductionQrcodes);
        }
    }

    private String getBase64(Product productInfo, String worksNo, String tokenId, String time) {

        try{
            Map<String, Object> keyWordMap = new HashMap<>();

            keyWordMap.put("name","");
            keyWordMap.put("worksNo",worksNo);
            keyWordMap.put("worksTypeName","字画");
            Map<String,String> imageMap = new HashMap<>();

            Minio minio = shopConfig.getMinio();
            keyWordMap.put("worksName",productInfo.getProdName());
            imageMap.put("worksImg",minio.getEndpoint() + "/" + minio.getBucketName() + "/" + productInfo.getPic());
            ProdNft prodNft = prodNftService.getDataByProdId(productInfo.getProdId());
            keyWordMap.put("autherName",prodNft.getAuthorName());
            keyWordMap.put("tokenId","待上链");
            if (StringUtils.isNotEmpty(tokenId)) {
                keyWordMap.put("tokenId",tokenId);
            }
            keyWordMap.put("time","待上链");
            if (StringUtils.isNotEmpty(time)) {
                keyWordMap.put("time",time);
            }

            URL url = new URL(minio.getEndpoint() + "/" + minio.getBucketName() + "/cqdj.pdf");
            URLConnection urlConnection = url.openConnection();
            urlConnection.connect();
            ByteArrayOutputStream qrOutputStream = new ByteArrayOutputStream();
            PdfUtils.generatePdf(urlConnection.getInputStream(), qrOutputStream, keyWordMap,imageMap,35f);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ByteArrayOutputStream scaleOutputStream = new ByteArrayOutputStream();
            //保存图片
            PDDocument document = PDDocument.load(qrOutputStream.toByteArray());
            PDFRenderer pdfRenderer = new PDFRenderer(document);
            BufferedImage image = pdfRenderer.renderImageWithDPI(0, 300); // 使用300dpi解析第一页，可以自行调整dpi大小
            ImageIO.write(image, "JPEG", outputStream);
            MultipartFile ossMultipartFile = new OssMultipartFile("111.jpg", ".jpg", outputStream.toByteArray());
            ImgUtil.scale(ossMultipartFile.getInputStream(),scaleOutputStream,0.1f);

            return attachFileService.uploadFile(scaleOutputStream.toByteArray(), UUID.randomUUID() + ".jpg");
        }catch (Exception e){
            e.printStackTrace();
            return "";
        }
    }
}
